#pragma once

#include <iostream>
#include <string>
#include <unordered_map>

#include "TcpServer.hpp"
#include "HttpProtocol.hpp"

using namespace TcpServerModule;

using http_handler_t = std::function<void(HttpRequest&, HttpResponse&)>;


class HttpServer
{
public:
    HttpServer(int port)
        : _tsvr(std::make_unique<TcpServer>(port))
    {
    }
    void Register(const std::string & svr_name, http_handler_t handler_func)
    {
        _router[svr_name] = handler_func;
    }
    bool SafeCheck(const std::string & svr_name)
    {
        // 检查是否有对应的服务，有就说明安全；
        auto iter = _router.find(svr_name);
        return iter != _router.end();
    }

    void Start()
    {
        _tsvr->InitServer([this](SockPtr sockp, InetAddr client)
                          { this->HandelrRequest(sockp, client); }); // lambda表达式对 HandlerRequest的引用
        _tsvr->Loop();
    }
    bool HandelrRequest(SockPtr sockp, InetAddr client)
    {
        LOG(LogLevel::DEBUG) << "get a new client: " << sockp->Fd() << " addr info: " << client.Addr();
        std::string http_request;
        
        // 读取完整性判断--先不管了
        sockp->Recv(&http_request);
        HttpRequest req;
        req.Deserialize(http_request);
        HttpResponse resp;
        if(req.IsHasArgs())
        {
            // 动态资源 交互性设置
            LOG(LogLevel::DEBUG) << "-----Has Args-----";
            std::string service = req.Path();
            if(SafeCheck(service)) // 查看是否注册service
            {
                _router[service](req, resp);
            }
            else{
                resp.Build(req);
            }

        }
        else{
            LOG(LogLevel::DEBUG) << "-----Args None-----";
            resp.Build(req);
        }
        std::string resp_str;
        resp.Serialize(&resp_str);
        sockp->Send(resp_str);
        return true;
//         std::cout << http_request;
//         // 读取请求 处理（文本处理
//         // 1. 读取的完整性
//         // 2. 完整的http反序列化，http response 序列化
//         // demo 1 : 直接返回固定内容
//         std::string status_line = "HTTP/1.1 200 OK" + sep + blankline;

//         std::string body = R"(<!DOCTYPE html>
// <html lang="en">
// <head>
//     <meta charset="UTF-8">
//     <title>Hello World</title>
// </head>
// <body>
//     <h1>Hello, World!</h1>
// </body>
// </html>)";
//         std::string httpresponse = status_line + body;
//         sockp->Send(httpresponse);
    }
    ~HttpServer() {}

private:
    std::unique_ptr<TcpServer> _tsvr;

    std::unordered_map<std::string, http_handler_t> _router;

};